package de.unistuttgart.iaaskpimonitoring.esper.processingmanagement.nodeImpl;

import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import com.espertech.esper.client.EPServiceProvider;

import de.unistuttgart.iaaskpimonitoring.esper.processingmanagement.MMOperatorNode;
import de.unistuttgart.iaaskpimonitoring.esper.processingmanagement.NodeFactory;

public class CountNodeFactory implements NodeFactory {

	public MMOperatorNode createNode(Element DOMElement,
			Element attachmentsElement, MMOperatorNode parent,
			EPServiceProvider EPService) {

		MMOperatorNode toReturn = new MMOperatorNode();

		// Attributes independent of the children
		toReturn.setOutputStreamName("count"
				+ (++MMOperatorNode.nodeLatestDistributedID));
		toReturn.setOutputMetric("count");

		toReturn.setParent(parent);

		/*
		 * Parameters to get : activityID
		 */
		Element attachment = null;
		NodeList attachments = attachmentsElement
				.getElementsByTagName("attachment");
		for (int i = 0; i < attachments.getLength(); i++) {
			if (((Element) attachments.item(i))
					.getAttributeNode("attachmentID").getNodeValue().equals(
							DOMElement.getAttributeNode("attachmentID")
									.getNodeValue())) {
				attachment = (Element) attachments.item(i);
			}
		}
		// toReturn.setParameters();

		// Children nodes not for atomic operator like state, duration, count
		// etc.
		/*
		 * NodeList childrenElements = DOMElement.getChildNodes(); if
		 * (childrenElements.getLength() > 0) { List<MMOperatorNode> children =
		 * new ArrayList<MMOperatorNode>(4); for (int i = 0; i <
		 * childrenElements.getLength(); i++) { Element currentChildRoot =
		 * (Element) childrenElements.item(i);
		 * children.add(NodeFactoryManager.getInstance(
		 * currentChildRoot.getLocalName()).createNode( currentChildRoot,
		 * attachmentsElement, toReturn, EPService)); }
		 * 
		 * toReturn.getChildren(); toReturn.setChildren(children); }
		 */

		String statementString = new String(
				"INSERT INTO "
						+ toReturn.getOutputStreamName()
						+ " SELECT "
						+ " count(*) AS  "
						+ toReturn.getOutputMetric()
						+ ", "
						+ " processInstanceID AS processInstanceID, "
						+ " de.unistuttgart.iaaskpimonitoring.esper.eventmanagement.EventUtils.addInCorrelationSet(processInstanceID) AS correlationSet,"
						+ " *");

		statementString
				.concat(" FROM de.unistuttgart.iaaskpimonitoring.esper.eventmanagement.ActivityEvent(name = 'ActivityCompletionEvent'"
						+ "and activityID = "
						+ toReturn.getParameters().get("activityID"));

		// Creation of the statement that is directly registered in the engine !
		toReturn.setStatement(EPService.getEPAdministrator().createEPL(
				statementString));

		return toReturn;
	}

}
